﻿using System;
using System.Collections.Generic;

namespace PlottingBasics.LINQHelpers
{
    /// <summary>
    /// Does a condition on the sequence
    /// </summary>
    public static class Condition
    {
        public static IEnumerable<TResult> Conditional<TSource, TResult>(this IEnumerable<TSource> source,
            Func<TSource, bool> tester,
            Func<TSource, TResult> useIfTestTrue,
            Func<TSource, TResult> useIfTestFalse)
        {
            return new ConditionalItr<TSource, TResult>(source, tester, useIfTestTrue, useIfTestFalse);
        }

        class ConditionalItr<TSource, TResult> : IEnumerable<TResult>
        {
            private IEnumerable<TSource> _source;
            private Func<TSource, bool> _tester;
            private Func<TSource, TResult> _useIfTestTrue;
            private Func<TSource, TResult> _useIfTestFalse;

            public ConditionalItr(IEnumerable<TSource> source, Func<TSource, bool> tester, Func<TSource, TResult> useIfTestTrue, Func<TSource, TResult> useIfTestFalse)
            {
                // TODO: Complete member initialization
                this._source = source;
                this._tester = tester;
                this._useIfTestTrue = useIfTestTrue;
                this._useIfTestFalse = useIfTestFalse;
            }

            public System.Collections.Generic.IEnumerator<TResult> GetEnumerator()
            {
                foreach (var p in _source)
                {
                    if (_tester(p))
                    {
                        yield return _useIfTestTrue(p);
                    }
                    else
                    {
                        yield return _useIfTestFalse(p);
                    }
                }
            }

            #region IEnumerable Members

            System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
            {
                throw new NotImplementedException();
            }

            #endregion
        }
    }
}
